import React, { useState } from 'react';
import { Link, Outlet, useLocation } from 'react-router-dom';
import {
  Users,
  Home,
  ChevronRight,
  CreditCard,
  LogOut,
  User,
  ChevronDown,
  Video,
  FileText,
  Bot,
  Target,
} from 'lucide-react';
import ActiveAccount from './ActiveAccount';
import { useAuthStore } from '../stores/authStore';
import { authApi } from '../api';
import { toast } from '../stores/toastStore';
import { useConfirm } from '../hooks/useConfirm';

const Layout: React.FC = () => {
  const location = useLocation();
  const { admin, logout } = useAuthStore();
  const { confirm, setLoading: setConfirmLoading, ConfirmComponent } = useConfirm();
  const [showUserMenu, setShowUserMenu] = useState(false);

  const handleLogout = async () => {
    const confirmed = await confirm({
      title: '确认退出',
      message: '您确定要退出登录吗？',
      confirmText: '退出登录',
    });

    if (!confirmed) return;

    try {
      setConfirmLoading(true);
      await authApi.logout();
      toast.success('已成功退出登录');
    } catch (error) {
      console.error('Logout error:', error);
      toast.warning('退出时发生错误，但本地登录状态已清除');
    } finally {
      setConfirmLoading(false);
      logout();
    }
  };

  const menuItems = [
    { path: '/', icon: Home, label: '仪表盘' },
    { path: '/accounts', icon: CreditCard, label: 'HeyGen账户' },
    { path: '/ai-providers', icon: Bot, label: 'AI服务商' },
    { path: '/avatars', icon: Users, label: '虚拟形象' },
    { path: '/videos', icon: Video, label: '视频管理' },
    { path: '/text-generation', icon: FileText, label: '文案生成' },
    { path: '/user-persona', icon: Target, label: '用户画像' },
  ];

  return (
    <div className="min-h-screen bg-gray-950 text-gray-100">
      {/* Header */}
      <header className="bg-gray-900 border-b border-gray-800">
        <div className="px-6 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <div className="flex items-center space-x-2">
                <div className="w-8 h-8 bg-gray-200 rounded flex items-center justify-center">
                  <img src="/favicon.svg" alt="Digital Me Logo" className="w-6 h-6" />
                </div>
                <h1 className="text-2xl font-bold bg-gradient-to-r from-cyan-400 to-blue-500 bg-clip-text text-transparent">
                  黑梗ai
                </h1>
              </div>
              <span className="text-sm text-gray-500">AI视频平台</span>
            </div>
            <div className="flex items-center space-x-4">
              <ActiveAccount />

              {/* User Menu */}
              <div className="relative">
                <button
                  onClick={() => setShowUserMenu(!showUserMenu)}
                  className="flex items-center space-x-2 px-3 py-2 rounded-lg hover:bg-gray-800 transition-colors cursor-pointer"
                >
                  <div className="w-8 h-8 bg-gradient-to-br from-cyan-500 to-blue-600 rounded-full flex items-center justify-center">
                    <User className="w-5 h-5 text-white" />
                  </div>
                  <span className="text-sm text-gray-300">{admin?.username}</span>
                  <ChevronDown className="w-4 h-4 text-gray-400" />
                </button>

                {showUserMenu && (
                  <div className="absolute right-0 mt-2 w-48 bg-gray-800 border border-gray-700 rounded-lg shadow-lg z-10">
                    <div className="px-4 py-3 border-b border-gray-700">
                      <p className="text-sm font-medium text-gray-200">{admin?.username}</p>
                      <p className="text-xs text-gray-400">{admin?.email}</p>
                    </div>
                    <button
                      onClick={handleLogout}
                      className="w-full flex items-center space-x-2 px-4 py-2 text-sm text-gray-300 hover:bg-gray-700 transition-colors cursor-pointer"
                    >
                      <LogOut className="w-4 h-4" />
                      <span>退出登录</span>
                    </button>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </header>

      <div className="flex">
        {/* Sidebar */}
        <aside className="w-64 bg-gray-900 border-r border-gray-800 min-h-[calc(100vh-73px)]">
          <nav className="p-4">
            {menuItems.map(item => {
              const Icon = item.icon;
              const isActive = location.pathname === item.path;
              return (
                <Link
                  key={item.path}
                  to={item.path}
                  className={`flex items-center space-x-3 px-4 py-3 rounded-lg mb-2 transition-all cursor-pointer ${
                    isActive
                      ? 'bg-gradient-to-r from-cyan-500/20 to-blue-500/20 text-cyan-400 border border-cyan-500/30'
                      : 'hover:bg-gray-800 text-gray-400 hover:text-gray-200'
                  }`}
                >
                  <Icon className="w-5 h-5" />
                  <span className="font-medium">{item.label}</span>
                  {isActive && <ChevronRight className="w-4 h-4 ml-auto" />}
                </Link>
              );
            })}
          </nav>
        </aside>

        {/* Main Content */}
        <main className="flex-1 p-6">
          <Outlet />
        </main>
      </div>

      {/* Unified Confirm Dialog */}
      <ConfirmComponent />
    </div>
  );
};

export default Layout;
